package com.haidechizi.i18n.common.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.haidechizi.i18n.common.constant.ParamConstant;
import com.haidechizi.i18n.common.utils.GlobalUtils;

/**
 * 接受消费端传递过来的参数，将translate变量放到ThreadLocal中
 */
@Activate(group = Constants.PROVIDER, order = -500)
public class ProviderTranslateFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            GlobalUtils.setTranslate(invocation.getAttachment(ParamConstant.TRANSLATE));
            return invoker.invoke(invocation);
        } finally {
            // 移除ThreadLocal中的变量，防止出现内存泄漏
            GlobalUtils.clear();
        }
    }
}
